package com.hongdee.crm.workorder.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.dao.IImpHibernateDao;
import com.hongdee.common.dao.IImpJdbcDao;
import com.hongdee.common.dao.IJdbcDao;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.saMessage.service.ITCrmCarSaMessageService;
import com.hongdee.crm.task.service.ICarBaseCountService;
import com.hongdee.crm.task.service.ITCrmCarWorkorderTaskService;
import com.hongdee.crm.workorder.entity.TCrmCarWorkOrder;
import com.hongdee.crm.workorder.service.ITCrmCarWorkOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

//import sun.java2d.pipe.AAShapePipe;


import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * 名  称:TCrmCarWorkOrderServiceImpl
 * 类  型: class
 * 描  述:
 * 路  径:com.hongdee.crm.workorder.service.impl;
 * 作  者: 术洪超
 * 日  期:2017-02-22 15:49
 */
@Service
public class TCrmCarWorkOrderServiceImpl implements ITCrmCarWorkOrderService {

    private String tabName = "T_CRM_CAR_WORKORDER";
    private String EXIST_DATA_SQL = "select * from " + tabName + " where order_num = ? and company_id = ? limit 1";

    @Autowired
    private IImpJdbcDao iImpJdbcDao;

    @Autowired
    private IImpHibernateDao iImpHibernateDao;

    @Autowired
    private IJdbcDao iJdbcDao;

    @Autowired
    private IHibernateDao iHibernateDao;

    @Autowired
    private ITCrmCarWorkorderTaskService itCrmCarWorkorderTaskService;

    @Autowired
    private ITCrmCarSaMessageService itCrmCarSaMessageService;

    @Autowired
    private ICarBaseCountService iCarBaseCountService;

    @Override
    public Map impPage(String uid, String start, String limit) throws Exception {
        String sql = "select * from " + tabName + " where company_id = ? ";
        String oId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        params.add(oId);
        return iImpJdbcDao.queryForPageMap(start, limit, sql, params.toArray());
    }

    @Override
    public void impDel(String id) throws Exception {
        String sql = "delete from TCrmCarWorkOrder where id = :id ";
        Map params = new HashMap();
        params.put("id", id);
        this.iImpHibernateDao.executeHqlWithParams(sql, params);

    }

    @Override
    public void impConfirm(String id, String uid) throws Exception {

        Object obj = iImpHibernateDao.findEntity(TCrmCarWorkOrder.class, id);
        if (obj == null) {
            throw new Exception("无对应数据！");
        }
        TCrmCarWorkOrder workOrder = (TCrmCarWorkOrder) obj;

        //根据维修业务工单号、公司 ID、车架号查询记录是否已经存在
        Map existData = this.iJdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, workOrder.getOrderNum(), workOrder.getCompanyId());
        if (existData.size() == 0) {
            //新数据
            workOrder.setId(null);
            workOrder.setCreateTime(new Date().getTime());
            workOrder.setUpdateTime(new Date().getTime());
            workOrder.setConfirmer(uid);
            workOrder.setConfirmDate(new Date().getTime());
        } else {
            //已有数据
            workOrder.setId(existData.get("id").toString());
            workOrder.setUpdateTime(new Date().getTime());
            workOrder.setConfirmer(uid);
            workOrder.setConfirmDate(new Date().getTime());
        }

        this.iHibernateDao.saveOrUpdateEntity(workOrder);
        this.impDel(id);

        //调用生成SA消息提醒
        this.itCrmCarSaMessageService.saveOrder(uid);
    }

    @Override
    public void impConfirms(List<Map<Object, String>> data, String uid) throws Exception {
        if (data.size() == 0) {
            throw new Exception("请选择需要确认数据");
        }
        TCrmCarWorkOrder workOrder;
        Map existData;
        List<Object> idList = new ArrayList<>();
        for (Map orderId : data) {
            String idStr = String.valueOf(orderId.get("id"));
            idList.add(idStr);
            //根据id查询销售实体
            Object obj = iImpHibernateDao.findEntity(TCrmCarWorkOrder.class, idStr);
            if (obj == null) {
                throw new Exception("无效的数据！");
            }
            workOrder = (TCrmCarWorkOrder) obj;
            //根据vin判断主表立是否已存在
            existData = this.iJdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, workOrder.getOrderNum(), workOrder.getCompanyId());
            if (existData.size() == 0) {
                //新数据
                workOrder.setId(null);
                workOrder.setCreateTime(new Date().getTime());
                workOrder.setUpdateTime(new Date().getTime());
                workOrder.setConfirmer(uid);
                workOrder.setConfirmDate(new Date().getTime());
            } else {
                //已有数据
                workOrder.setId(existData.get("id").toString());
                workOrder.setUpdateTime(new Date().getTime());
                workOrder.setConfirmer(uid);
                workOrder.setConfirmDate(new Date().getTime());
            }
            //保存或更新
            this.iHibernateDao.saveOrUpdateEntity(workOrder);

        }

        this.iImpJdbcDao.batchDel(tabName, "id", idList);
        idList.clear();
        //调用工单产值计算
        this.itCrmCarWorkorderTaskService.updWorkOrderAmountInfoQuartz();
        //调用计算车辆id
        this.itCrmCarWorkorderTaskService.updWorkOrderCaridInfoQuartz();

        //调用生成SA消息提醒
        this.itCrmCarSaMessageService.saveOrder(uid);
    }

    @Override
    public void impConfirmAll(String uid) throws Exception {
        //获取公司 ID
        String companyId = TokenUtil.getCompanyId(uid);

        //  //目标数据库
        String targetSchema = iHibernateDao.Schema();
        //来源数据库
        String sourceSchema = iImpHibernateDao.Schema();

        if (StringUtils.isEmpty(targetSchema) || StringUtils.isEmpty(sourceSchema)) {
            throw new Exception("未获取到数据库实例请联系管理员");
        }

        //更新语句
        StringBuffer updateSQL = new StringBuffer();
        updateSQL.append("update " + targetSchema + ".t_crm_car_workorder c1, " +
                "(SELECT id, create_time, create_user, update_time, update_user, avg_mile, avgby_mile, SUM(balance_amount) balance_amount, balance_date, brand, car_age, " +
                "car_id, clear_date, company_id, confirm_date, confirmer, demand_num, expect_date, finish_date, is_finished, SUM(maintain_amount) maintain_amount, " +
                "maintain_type, maintaintype_id, model, open_date, order_num, order_status, `owner`, plate_num, SUM(receive_amount) receive_amount, receptor, " +
                "run_mile, sa_group_id, sa_id, send_car_date, sender, series, `status`, test_operator, type, user_code, vin, yb_status, yb_type, real_amount, wx_type, sender_tel,organ_name,type_group,product_name " +
                "FROM "+sourceSchema+".t_crm_car_workorder GROUP BY order_num,company_id,plate_num,type) c2 " +
                //"       " + sourceSchema + ".t_crm_car_workorder c2" +
                "   SET ");
        updateSQL.append(" c1.avg_mile=c2.avg_mile,");
        updateSQL.append(" c1.avgby_mile=c2.avgby_mile,");
        updateSQL.append(" c1.balance_amount=c2.balance_amount,");
        updateSQL.append(" c1.balance_date=c2.balance_date,");
        updateSQL.append(" c1.brand=c2.brand,");
        updateSQL.append(" c1.car_age=c2.car_age,");
        updateSQL.append(" c1.car_id=c2.car_id,");
        updateSQL.append(" c1.clear_date=c2.clear_date,");
        updateSQL.append(" c1.company_id=c2.company_id,");
        updateSQL.append(" c1.confirm_date=c2.confirm_date,");
        updateSQL.append(" c1.confirmer=c2.confirmer,");
        updateSQL.append(" c1.demand_num=c2.demand_num,");
        updateSQL.append(" c1.expect_date=c2.expect_date,");
        updateSQL.append(" c1.finish_date=c2.finish_date,");
        updateSQL.append(" c1.is_finished=c2.is_finished,");
        updateSQL.append(" c1.maintain_amount=c2.maintain_amount,");
        updateSQL.append(" c1.maintain_type=c2.maintain_type,");
        updateSQL.append(" c1.maintaintype_id=c2.maintaintype_id,");
        updateSQL.append(" c1.model=c2.model,");
        updateSQL.append(" c1.open_date=c2.open_date,");
        updateSQL.append(" c1.order_num=c2.order_num,");
        updateSQL.append(" c1.order_status=c2.order_status,");
        updateSQL.append(" c1.owner=c2.owner,");
        updateSQL.append(" c1.plate_num=c2.plate_num,");
        updateSQL.append(" c1.receive_amount=c2.receive_amount,");
        updateSQL.append(" c1.receptor=c2.receptor,");
        updateSQL.append(" c1.run_mile=c2.run_mile,");
        updateSQL.append(" c1.sa_group_id=c2.sa_group_id,");
        updateSQL.append(" c1.sa_id=c2.sa_id,");
        updateSQL.append(" c1.send_car_date=c2.send_car_date,");
        updateSQL.append(" c1.sender=c2.sender,");
        updateSQL.append(" c1.series=c2.series,");
        updateSQL.append(" c1.status=c2.status,");
        updateSQL.append(" c1.test_operator=c2.test_operator,");
        updateSQL.append(" c1.type=c2.type,");
        updateSQL.append(" c1.user_code=c2.user_code,");
        updateSQL.append(" c1.vin=c2.vin,");
        updateSQL.append(" c1.yb_status=c2.yb_status,");
        updateSQL.append(" c1.yb_type=c2.yb_type,");
        updateSQL.append(" c1.real_amount=c2.real_amount,");
        updateSQL.append(" c1.wx_type=c2.wx_type,");
        updateSQL.append(" c1.sender_tel=c2.sender_tel, ");
        updateSQL.append(" c1.organ_name=c2.organ_name, ");
        updateSQL.append(" c1.type_group=c2.type_group, ");
        updateSQL.append(" c1.product_name=c2.product_name ");
        //updateSQL.append(" c1.sp_type=c2.sp_type");
        // updateSQL.append(" c1.bu_type=c2.bu_type ");
        updateSQL.append("  where c1.order_num  = c2.order_num and c2.company_id =c1.company_id  and c1.company_id ='" + companyId + "' ");

        //删除语句
        StringBuffer delExistSQL = new StringBuffer();

        String targeTable = targetSchema + ".t_crm_car_workorder";
        String sourceTable = sourceSchema + ".t_crm_car_workorder";

        delExistSQL.append("delete from " + sourceTable + " USING " + targeTable + "," + sourceTable + " WHERE ");
        delExistSQL.append(" " + targeTable + ".company_id = " + sourceTable + ".company_id  and " + targeTable + ".order_num  = " + sourceTable + ".order_num  and " + targeTable + ".company_id ='" + companyId + "'");

        //新增语句
        StringBuffer insertSQL = new StringBuffer();
        StringBuffer selectField = new StringBuffer();
        selectField.append("     id, ");
        selectField.append("    create_time, ");
        selectField.append("    create_user, ");
        selectField.append("    update_time, ");
        selectField.append("    update_user, ");
        selectField.append("    avg_mile, ");
        selectField.append("    avgby_mile, ");
        selectField.append("    balance_amount, ");
        selectField.append("    balance_date, ");
        selectField.append("    brand, ");
        selectField.append("    car_age, ");
        selectField.append("    car_id, ");
        selectField.append("    clear_date, ");
        selectField.append("    company_id, ");
        selectField.append("    confirm_date, ");
        selectField.append("    confirmer, ");
        selectField.append("    demand_num, ");
        selectField.append("    expect_date, ");
        selectField.append("    finish_date, ");
        selectField.append("    is_finished, ");
        selectField.append("    maintain_amount, ");
        selectField.append("    maintain_type, ");
        selectField.append("    maintaintype_id, ");
        selectField.append("    model, ");
        selectField.append("    open_date, ");
        selectField.append("    order_num, ");
        selectField.append("    order_status, ");
        selectField.append("    owner, ");
        selectField.append("    plate_num, ");
        selectField.append("    receive_amount, ");
        selectField.append("    receptor, ");
        selectField.append("    run_mile, ");
        selectField.append("    sa_group_id, ");
        selectField.append("    sa_id, ");
        selectField.append("    send_car_date, ");
        selectField.append("    sender, ");
        selectField.append("    series, ");
        selectField.append("    status, ");
        selectField.append("    test_operator, ");
        selectField.append("    type, ");
        selectField.append("    user_code, ");
        selectField.append("    vin, ");
        selectField.append("    yb_status, ");
        selectField.append("    yb_type, ");
        selectField.append("    real_amount, ");
        selectField.append("    wx_type, ");
        selectField.append("    sender_tel, ");
        selectField.append("    organ_name, ");
        selectField.append("    type_group, ");
        selectField.append("    product_name ");
        //selectField.append("    sp_type ");
        // selectField.append("    bu_type ");

        insertSQL.append(" insert into " + targetSchema + ".t_crm_car_workorder(").append(selectField.toString()).append(") ").append(" select " +
                "id, create_time, create_user, update_time, update_user, avg_mile, avgby_mile, SUM(balance_amount) balance_amount, balance_date, brand, car_age, " +
                "car_id, clear_date, company_id, confirm_date, confirmer, demand_num, expect_date, finish_date, is_finished, SUM(maintain_amount) maintain_amount, " +
                "maintain_type, maintaintype_id, model, open_date, order_num, order_status, `owner`, plate_num, SUM(receive_amount) receive_amount, receptor, " +
                "run_mile, sa_group_id, sa_id, send_car_date, sender, series, `status`, test_operator, type, user_code, vin, yb_status, yb_type, real_amount, wx_type, sender_tel,organ_name,type_group,product_name " +
                "FROM " + sourceSchema + ".t_crm_car_workorder where  company_id = '" + companyId + "' GROUP BY order_num,company_id,plate_num,type ");
        // insertSQL.append(selectField.toString()).append(" from " + sourceSchema + ".t_crm_car_workorder where  company_id = '" + companyId + "'");
        //更新记录数
        int upRowCount = iJdbcDao.update(updateSQL.toString());
        System.out.println("-------------updateNum------更新工单数------" + upRowCount);
        //删除更新记录数
        int delRowCount = iJdbcDao.update(delExistSQL.toString());
        System.out.println("--------------deleteTheUpdateNum-----删除更新工单数-------" + delRowCount);

        //新增记录数
        int addRowCount = iJdbcDao.update(insertSQL.toString());
        System.out.println("-------------insertNum------新增工单数-------" + addRowCount);

        //删除新增记录数
        int delAddRowCount = iJdbcDao.update(delExistSQL.toString());

        System.out.println("-------------deleteTheInsertNum-----删除新增工单数------" + delAddRowCount);


//        //编写查询源数据 HQL
//        String hql = "from TCrmCarWorkOrder where companyId = :companyId";
//        //设置参数
//        Map<String, Object> params = new HashMap();
//        params.put("companyId", companyId);
//        //查询公司下的全部车辆
//        List<TCrmCarWorkOrder> tCrmCarWorkOrder = iImpHibernateDao.findEntityListByHqlWithParams(hql, params);
//        if (tCrmCarWorkOrder == null) {
//            throw new Exception("无效的数据！");
//        }
//
//        //每50条保存一次
//        List<Object> idList = new ArrayList<>();
//        Map existData;
//        String tempId;
//        for (TCrmCarWorkOrder workOrder : tCrmCarWorkOrder) {
//            //根据vin判断主表立是否已存在
//            existData = this.iJdbcDao.queryForMapBySqlWithParams(EXIST_DATA_SQL, workOrder.getOrderNum(), workOrder.getCompanyId());
//            tempId = workOrder.getId();
//            idList.add(tempId);
//            if (existData.size() == 0) {
//                //新数据
//                workOrder.setId(null);
//                workOrder.setCreateTime(new Date().getTime());
//                workOrder.setUpdateTime(new Date().getTime());
//                workOrder.setConfirmer(uid);
//                workOrder.setConfirmDate(new Date().getTime());
//            } else {
//                //已有数据
//                workOrder.setId(existData.get("id").toString());
//                workOrder.setUpdateTime(new Date().getTime());
//                workOrder.setConfirmer(uid);
//                workOrder.setConfirmDate(new Date().getTime());
//            }
//            //保存或更新
//            this.iHibernateDao.saveOrUpdateEntity(workOrder);
//            if (idList.size() == 500) {
//                this.iImpJdbcDao.batchDel(tabName, "id", idList);
//                idList.clear();
//            }
//        }
//        //处理剩余数据
//        if (idList.size() > 0) {
//            this.iImpJdbcDao.batchDel(tabName, "id", idList);
//            idList.clear();
//        }

//        //调用计算车辆id
//        this.itCrmCarWorkorderTaskService.updWorkOrderCaridInfoQuartz();
//        //工单类型更新
//        this.itCrmCarWorkorderTaskService.bulidWorkorderPropertyByCompanyQuqrtz(companyId);
//        //索赔类型更新
//        this.itCrmCarWorkorderTaskService.bulidWorkorderPropertyBySpCompanyQuartz(companyId);
//        //调用工单产值计算
//        this.itCrmCarWorkorderTaskService.updWorkOrderAmountInfoQuartz();
//        //调用生成SA消息提醒
//        this.itCrmCarSaMessageService.saveOrder(uid);
//        //车型车系同步
//        this.iCarBaseCountService.updateExCarSeriesQuartz();
    }

    /**
     * 工单查询
     */
    @Override
    public Map workOrderQuery(String uid, String vin,String companyId,String typePCode,String typeCode) throws Exception {
        StringBuffer sqlSH = new StringBuffer();
        StringBuffer ybSql = new StringBuffer();
        StringBuffer xbSql = new StringBuffer();
        List params = new ArrayList();
        List workItem = new ArrayList();
        List ybParams = new ArrayList();
        List xbParams = new ArrayList();
        Map data = new HashMap();
        if("".equals(companyId)){
            companyId=TokenUtil.getCompanyId(uid);
        }
        /**
         * companyid
         * vin
         * 延保查询
         */
        ybSql.append("select restart_insurance,restop_insurance,type_name,start_legend, stop_legend,mile_status from t_crm_car_exsurance  where vin = ? and company_id=? ");
        ybParams.add(vin);
        ybParams.add(companyId);
        List<Map<String, Object>> ybList = this.iJdbcDao.queryForMapListBySqlWithParams(ybSql.toString(), ybParams.toArray());

        /**
         * companyid
         * vin
         * 续保查询
         */
        xbSql.append("select compulsoryinsurancenum,compulsory_start_date,compulsory_end_date,commercialinsurancenum , contractstartinsurance," +
                "contractstopinsurance,base_type,continuation from t_crm_car_insurance where vin = ? and company_id=? ");
        xbParams.add(vin);
        xbParams.add(companyId);
        List<Map<String, Object>> xbList = this.iJdbcDao.queryForMapListBySqlWithParams(xbSql.toString(), xbParams.toArray());

        /**
         * 获得延保、续保sql片段
         */
        String xbStr = getXbStr(xbList);
        String ybStr = getYbStr(ybList);
        String xbybStr = xbStr + ybStr;

        sqlSH.append(" SELECT w.*, c.cx_tag,IF(balance_amount>100,'核心客户',NULL) AS hxkh " + xbybStr + " from T_CRM_CAR_WORKORDER w LEFT JOIN t_crm_car c ON w.plate_num = c.plate_num where ");
        sqlSH.append("  w.vin = ? and w.company_id = ?  ");
        params.add(vin);
        params.add(companyId);

        if(typePCode.equals("zh") && typeCode.equals("srhf")){ // 如果是三日回访的任务
            sqlSH.append("AND EXISTS (SELECT 1 FROM t_crm_car_workitem i WHERE i.order_code = w.order_num AND i.company_id = w.company_id AND  i.maintain_type NOT LIKE '%洗车%') ");
        }
        if (typePCode.equals("by")){ // 如果是保养的或者是美容的任务
            sqlSH.append(" AND EXISTS (SELECT 1 FROM t_crm_car_workitem i WHERE i.order_code = w.order_num AND i.company_id = w.company_id AND  i.maintain_type = '机油机滤' ) ");
        }
        if (typePCode.equals("mr")){ // 如果是保养的或者是美容的任务
            sqlSH.append(" AND EXISTS (SELECT 1 FROM t_crm_car_workitem i WHERE i.order_code = w.order_num AND i.company_id = w.company_id AND  (i.maintain_type = '镀晶' or i.maintain_type = '打蜡' or i.maintain_type = '外饰套餐' or i.maintain_type = '内饰套餐')) ");
        }
        sqlSH.append(" order by w.balance_date desc limit 1");


        //String CompanyId = TokenUtil.getCompanyId(uid);

        List<Map<String, Object>> workOrder = this.iJdbcDao.queryForMapListBySqlWithParams(sqlSH.toString(), params.toArray());

        if (workOrder.size() != 0) {
            workItem = this.iJdbcDao.queryForMapListBySqlWithParams("select * from T_CRM_CAR_WORKITEM where order_code " +
                    "= ? and company_id = ? ", workOrder.get(0).get("order_num"), companyId);
        }

        // 判断是否为新客户，用于添加新客户标签----↓
        if(isNewCustomer(vin,companyId)){
            workOrder.get(0).put("newCustomer","新客户");
        }else {
            workOrder.get(0).put("newCustomer",null);
        }
        //判断是否为新客户，用于添加新客户标签-----↑

        data.put("workOrder", workOrder);
        data.put("workItem", workItem);
        return data;
    }

    /**
     * 根据vin查询车辆是否是第一次进厂
     * @param vin
     * @return
     */
    private boolean isNewCustomer(String vin,String companyId) throws Exception{
        String sql = "SELECT * FROM t_crm_car_workorder WHERE vin = ? AND company_id = ? GROUP BY order_num ";
        List params = new ArrayList();
        params.add(vin);
        params.add(companyId);
        List list = this.iJdbcDao.queryForMapListBySqlWithParams(sql,params.toArray());
        if(list.size()>1){
            return false;
        }
        return true;
    }

    /**
     * 获取sql片段函数
     * 延保
     *
     * @param ybList
     * @return
     */
    private String getYbStr(List<Map<String, Object>> ybList) {
        for (Map carInfoTemp : ybList) {
            if (carInfoTemp.get("mile_status") != null) {
                Integer mileStatus = Integer.valueOf(String.valueOf(carInfoTemp.get("mile_status")));
                if (mileStatus < 2) { //<2 添加延保标签
                    return ",'1' AS yb";
                }
            }
        }
        return ",'' AS yb";
    }

    /**
     * 获取sql片段函数
     * 续保
     *
     * @param xbList
     * @return
     */
    private String getXbStr(List<Map<String, Object>> xbList) {
        Long nowTime = new Date().getTime();
        for (Map carInfoTemp : xbList) {
            //商业险到期时间未过期
            if (carInfoTemp.get("contractstopinsurance") != null) { // contractstopinsurance 商业险到期时间
                Long contractstopinsurance = Long.valueOf(String.valueOf(carInfoTemp.get("contractstopinsurance")));
                if (contractstopinsurance > nowTime) {
                    String continuation = StringUtil.formatEmpty(carInfoTemp.get("continuation"));
                    return ",'1' AS xb, '" + continuation + "' AS continuation ";
                }
            }
            if (carInfoTemp.get("compulsory_end_date") != null) { // compulsory_end_date 交强险到期时间
                Long compulsoryEndDate = Long.valueOf(String.valueOf(carInfoTemp.get("compulsory_end_date")));
                if (compulsoryEndDate > nowTime) {
                    return ",'1' AS xb,'' as continuation";
                }
            }
        }
        return ",'' AS xb,'' as continuation";
    }

    /**
     * @return
     * @throws Exception
     * @desc 删除全部待导入数据
     * @author 术洪超
     */
    @Override
    public void impDelAll(String uid) throws Exception {

        Map map = new HashMap();
        String companyId = TokenUtil.getCompanyId(uid);
        String hql = " delete from TCrmCarWorkOrder where companyId =:companyId";
        map.put("companyId", companyId);
        //System.out.println(companyId);

        this.iImpHibernateDao.executeHqlWithParams(hql, map);
    }

    @Override
    public void impDels(List<Map<Object, String>> data, String uid) throws Exception {

        List<Object> idList = new ArrayList();
        for (Map map : data) {
            idList.add(map.get("id"));
        }
        this.iImpJdbcDao.batchDel(tabName, "id", idList);
    }

    /*
    *  @return
     * @throws Exception
     * @desc 根据Vin查询号查询历史工单项目历史（APP）
     * @author 于扬
    *
    * */
    public List appVin(String vin, String uid) throws Exception {
        List params = new ArrayList();
        String sql = "select balance_date,order_num,real_amount from t_crm_car_workorder where vin =? and company_id =? order by balance_date desc";
        params.add(vin);
        String cid = TokenUtil.getCompanyId(uid);
        params.add(cid);
        List<Map<String, Object>> mapList = this.iJdbcDao.queryForMapListBySqlWithParams(sql, params.toArray());
        List<Map> resList = new ArrayList<Map>();
        Map temp;
        /**
         * 通过遍历取得工单信息
         * */
        for (Map map : mapList) {
            String str1 = "";
            temp = new HashMap();
            temp.put("balanceDate", map.get("balance_date"));
            temp.put("orderNum", map.get("order_num"));
            temp.put("realAmount", map.get("real_amount"));
            /*
            * 把需要用来查询项目历史的工单号取出来
            * */
            str1 = String.valueOf(map.get("order_num"));
            /**
             * 项目历史
             * */
            String sql2 = "select item_name as name from t_crm_car_workitem where order_code =? and company_id =? ";
            List<Map<String, Object>> mapList2 = this.iJdbcDao.queryForMapListBySqlWithParams(sql2, str1, cid);
            System.out.print(str1);
            System.out.print(cid);
            List<Map> resList1 = new ArrayList<>();
            /**
             * 遍历项目历史 得到维修名
             * */

            for (Map map1 : mapList2) {
                Map temp2;
                temp2 = new HashMap<>();
                temp2.put("itemName", map1.get("name"));
                System.out.print(temp2);
                resList1.add(temp2);

            }

            temp.put("items", resList1);
            resList.add(temp);

        }
        return resList;
    }
}
